package com.manong.controller;

import com.manong.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 李茂鑫
 * @Date 2025/1/16 17:26
 * @Descripition
 */
public class UploadCountroller {
    @RestController
    @RequestMapping("/api/upload")
    public class UploadControllers {
        @PostMapping("/avatar")
        public Result uploadFile(@RequestParam("file") MultipartFile photo) throws IOException {
            //判断是否传入文件
            if (!photo.isEmpty()) {
                //文件上传地址
                String realPath="D:\\daima\\idea\\Permission_System\\system\\src\\main\\resources\\static\\img";
                //用于查看路径是否正确
                //获取文件的名称
                final String fileName = photo.getOriginalFilename();
                //限制文件类型
                String contentType = photo.getContentType();
                String url = "http://localhost:8888/img/"+fileName;
                if ("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) || "image/png".equals(contentType)) {
                    File file = new File(realPath, fileName);
                    //完成文件上传
                    photo.transferTo(file);
                    return Result.ok(url).message("上传成功");
                }else {
                    return Result.error().message("上传失败");
                }
            }
            return Result.error().message("上传失败");
        }
    }
}
